<template>
  <div class="assignment-stats">
    <div class="page-header">
      <h2>分配统计</h2>
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <div class="overview-cards">
      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #409eff">
            <el-icon><Tickets /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">总分配数</div>
            <div class="stat-value">{{ overview.total_assignments }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #e6a23c">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">待分配</div>
            <div class="stat-value">{{ overview.pending }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #67c23a">
            <el-icon><Check /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">已分配</div>
            <div class="stat-value">{{ overview.in_progress + overview.completed }}</div>
          </div>
        </div>
      </el-card>

      <el-card class="card">
        <div class="stat-item">
          <div class="stat-icon" style="background: #f56c6c">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-label">分配率</div>
            <div class="stat-value">{{ assignmentRate }}%</div>
          </div>
        </div>
      </el-card>
    </div>

    <div class="charts-row">
      <el-card class="chart-card">
        <template #header>
          <span>部门工单分配情况</span>
        </template>
        <div ref="departmentChartRef" class="chart"></div>
      </el-card>

      <el-card class="chart-card">
        <template #header>
          <span>员工工单分配排行</span>
        </template>
        <div ref="employeeChartRef" class="chart"></div>
      </el-card>
    </div>

    <el-card class="table-card">
      <template #header>
        <span>部门工单分配统计</span>
      </template>
      <el-table :data="departmentStats" stripe>
        <el-table-column prop="department_name" label="部门" width="200" />
        <el-table-column prop="total_count" label="工单总数" width="120" />
        <el-table-column prop="pending_count" label="待分配" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.pending_count > 0" type="danger">
              {{ scope.row.pending_count }}
            </el-tag>
            <span v-else>{{ scope.row.pending_count }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="in_progress_count" label="进行中" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.in_progress_count > 0" type="warning">
              {{ scope.row.in_progress_count }}
            </el-tag>
            <span v-else>{{ scope.row.in_progress_count }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="completed_count" label="已完成" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.completed_count > 0" type="success">
              {{ scope.row.completed_count }}
            </el-tag>
            <span v-else>{{ scope.row.completed_count }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成率" width="120">
          <template #default="scope">{{ getCompletionRate(scope.row) }}%</template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Tickets, Clock, Check, Warning, Refresh } from '@element-plus/icons-vue'

  const overview = reactive({
    total_assignments: 0,
    in_progress: 0,
    completed: 0,
    pending: 0,
  })

  const departmentStats = ref<any[]>([])
  const employeeStats = ref<any[]>([])

  const departmentChartRef = ref()
  const employeeChartRef = ref()

  const assignmentRate = computed(() => {
    if (overview.total_assignments === 0) return 0
    const assigned = overview.in_progress + overview.completed
    return ((assigned / overview.total_assignments) * 100).toFixed(1)
  })

  onMounted(() => {
    fetchOverviewData()
    fetchDepartmentStats()
    fetchEmployeeStats()
    initCharts()
  })

  const fetchOverviewData = async () => {
    try {
      const request = (await import('@/utils/request')).default
      const res = (await request({
        url: '/api/workorder/assignmentHistory/stats',
        method: 'get',
      })) as any
      if (res.code === 0) {
        Object.assign(overview, {
          total_assignments: res.data.total_assignments || 0,
          in_progress: res.data.in_progress || 0,
          completed: res.data.completed || 0,
          pending: res.data.pending || 0,
        })
      }
    } catch (error) {
      console.error('获取概览数据失败:', error)
      ElMessage.error('获取概览数据失败')
    }
  }

  const fetchDepartmentStats = async () => {
    try {
      const request = (await import('@/utils/request')).default
      const res = (await request({
        url: '/api/workorder/assignmentHistory/departmentStats',
        method: 'get',
      })) as any
      if (res.code === 0) {
        departmentStats.value = res.data || []
      }
    } catch (error) {
      console.error('获取部门统计失败:', error)
    }
  }

  const fetchEmployeeStats = async () => {
    try {
      const request = (await import('@/utils/request')).default
      const res = (await request({
        url: '/api/workorder/assignmentHistory/employeeStats',
        method: 'get',
      })) as any
      if (res.code === 0) {
        employeeStats.value = res.data.top_employees || []
      }
    } catch (error) {
      console.error('获取员工统计失败:', error)
    }
  }

  const chartInstances = ref<any[]>([])

  const initCharts = async () => {
    try {
      let echarts
      try {
        echarts = await import('echarts')
      } catch (importError) {
        console.error('ECharts 模块导入失败:', importError)
        ElMessage.error('图表组件加载失败')
        return
      }

      if (!echarts || typeof echarts.init !== 'function') {
        console.error('ECharts 库导入失败或不完整，缺少 init 方法')
        ElMessage.error('图表组件初始化失败')
        return
      }

      chartInstances.value.forEach(instance => {
        if (instance && typeof instance.dispose === 'function') {
          instance.dispose()
        }
      })
      chartInstances.value = []

      if (departmentChartRef.value && typeof departmentChartRef.value === 'object') {
        try {
          const chart = echarts.init(departmentChartRef.value)
          chartInstances.value.push(chart)

          const departments = departmentStats.value.map((item: any) => item.department_name)
          const pendingData = departmentStats.value.map((item: any) => item.pending_count)
          const inProgressData = departmentStats.value.map((item: any) => item.in_progress_count)
          const completedData = departmentStats.value.map((item: any) => item.completed_count)

          chart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow',
              },
            },
            legend: {
              data: ['待分配', '进行中', '已完成'],
            },
            xAxis: {
              type: 'category',
              data: departments,
            },
            yAxis: {
              type: 'value',
            },
            series: [
              {
                name: '待分配',
                type: 'bar',
                data: pendingData,
                itemStyle: { color: '#f56c6c' },
              },
              {
                name: '进行中',
                type: 'bar',
                data: inProgressData,
                itemStyle: { color: '#e6a23c' },
              },
              {
                name: '已完成',
                type: 'bar',
                data: completedData,
                itemStyle: { color: '#67c23a' },
              },
            ],
          })

          const resizeHandler = () => chart.resize()
          window.addEventListener('resize', resizeHandler)
          chartInstances.value.push({ instance: chart, resizeHandler: resizeHandler })
        } catch (chartError) {
          console.error('部门分配图初始化失败:', chartError)
        }
      }

      if (employeeChartRef.value && typeof employeeChartRef.value === 'object') {
        try {
          const chart = echarts.init(employeeChartRef.value)
          chart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow',
              },
            },
            legend: {
              data: ['工单总数', '已完成'],
            },
            xAxis: {
              type: 'value',
            },
            yAxis: {
              type: 'category',
              data: employeeStats.value.map((item: any) => item.employee_name).reverse(),
            },
            series: [
              {
                name: '工单总数',
                type: 'bar',
                data: employeeStats.value.map((item: any) => item.total_count).reverse(),
                itemStyle: { color: '#409eff' },
              },
              {
                name: '已完成',
                type: 'bar',
                data: employeeStats.value.map((item: any) => item.completed_count).reverse(),
                itemStyle: { color: '#67c23a' },
              },
            ],
          })

          const resizeHandler = () => chart.resize()
          window.addEventListener('resize', resizeHandler)
          chartInstances.value.push({ instance: chart, resizeHandler: resizeHandler })
        } catch (chartError) {
          console.error('员工排行图初始化失败:', chartError)
        }
      }
    } catch (error) {
      console.error('ECharts 初始化失败:', error)
    }
  }

  onUnmounted(() => {
    chartInstances.value.forEach(item => {
      if (item && item.resizeHandler) {
        window.removeEventListener('resize', item.resizeHandler)
      }
      if (item && item.instance && typeof item.instance.dispose === 'function') {
        item.instance.dispose()
      }
    })
    chartInstances.value = []
  })

  const handleRefresh = () => {
    fetchOverviewData()
    fetchDepartmentStats()
    fetchEmployeeStats()
    initCharts()
  }

  const getCompletionRate = (row: any) => {
    if (row.total_count === 0) return 0
    return ((row.completed_count / row.total_count) * 100).toFixed(1)
  }
</script>

<style lang="scss" scoped>
  .assignment-stats {
    padding: 20px;

    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .overview-cards {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20px;
      margin-bottom: 20px;

      .card {
        .stat-item {
          display: flex;
          align-items: center;
          gap: 15px;

          .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 24px;
          }

          .stat-content {
            .stat-label {
              font-size: 14px;
              color: #666;
              margin-bottom: 5px;
            }

            .stat-value {
              font-size: 28px;
              font-weight: bold;
              color: #333;
            }
          }
        }
      }
    }

    .charts-row {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 20px;
      margin-bottom: 20px;

      .chart-card {
        .chart {
          height: 350px;
        }
      }
    }

    .table-card {
      margin-bottom: 20px;
    }
  }

  @media (max-width: 1200px) {
    .overview-cards {
      grid-template-columns: repeat(2, 1fr) !important;
    }
    .charts-row {
      grid-template-columns: 1fr !important;
    }
  }

  @media (max-width: 768px) {
    .overview-cards {
      grid-template-columns: 1fr !important;
    }
  }
</style>
